package ${ServicePackageName};

import com.alibaba.fastjson.JSONObject;
import ${DaoPackageName}.${ClassName}Mapper;
import ${BasePackageName}.common.context.DefaultBusinessContext;
import  ${BasePackageName}.common.dto.WebResponseDto;
import ${EntityPackageName}.${ClassName};
import ${EntityPackageName}.${ClassName}Import;
import ${BasePackageName}.common.service.ImportService;
import ${BasePackageName}.common.enums.ApplicationEnum;
import ${BasePackageName}.common.util.MyStringUtils;
import ${BasePackageName}.common.util.RC4;
import ${BasePackageName}.common.util.cache.DataDictionaryUtil;
import ${BasePackageName}.easyexcel.definition.ExcelDefinitionReader;
import ${BasePackageName}.easyexcel.factory.DefinitionFactory;
import ${BasePackageName}.easyexcel.factory.xml.XMLDefinitionFactory4commonImport;
import ${BasePackageName}.easyexcel.resolver.poi.POIExcelResolver4commonImport;
import ${BasePackageName}.easyexcel.result.ExcelImportResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * @author: ${Author}
 * @date: ${DateTime}
 * @description:
 */
 @Service("${beanName}")
public class ${ClassName}ImportServiceImpl extends POIExcelResolver4commonImport implements ImportService{
    @Autowired
    private ${ClassName}Mapper ${EntityNameForCamelCase}Mapper;

    @Override
    protected ExcelDefinitionReader getExcelDefinition() {
        String xmlFullPath = "easyexcel/import/xml/${xmlName}.xml";
        DefinitionFactory definitionReaderFactory = new XMLDefinitionFactory4commonImport(xmlFullPath);
        return definitionReaderFactory.createExcelDefinitionReader();
    }

    @Override
    protected String getLookupItemCodeByName(String rootCode, String name) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        return DataDictionaryUtil.getLookupCodeByRootCodeAndName(ctx.getLocale().toString(),rootCode,name);
    }


    @Transactional(rollbackFor=Exception.class)
    @Override
    public WebResponseDto importByExcel(JSONObject jsonObject) {
        WebResponseDto mm = new WebResponseDto();

        DefaultBusinessContext ctx = jsonObject.getObject("ctx",DefaultBusinessContext.class);

        ExcelImportResult excelImportResult = null;
        try {
            byte[] fileBytes = jsonObject.getBytes("fileBytes");

            super.excelInputStream =  new ByteArrayInputStream(fileBytes);

            // 1.读取excel数据
            excelImportResult = super.readExcel();

            // 2.处理业务数据
            Map<String, List<?>> listMap = excelImportResult.getListMap();

            List<${ClassName}Import> imports = (List<${ClassName}Import>)listMap.get("0"); // 获取第1个sheet里面的数据
            if(CollectionUtils.isNotEmpty(imports)){
                int successCount = 0;
                int errorCount = 0;
                String errorMsg = "";

                Map resultMap = doImport(ctx,imports);
                successCount = Integer.parseInt(resultMap.get("successCount")+"");
                errorCount = Integer.parseInt(resultMap.get("errorCount")+"");
                errorMsg = resultMap.get("errorMsg")+"";

                if(successCount == imports.size()){
                    mm.setCode("A100502");
                    errorMsg = "全部导入成功，共["+successCount+"]条记录" + errorMsg;
                }else if(errorCount == imports.size()){
                    mm.setCode("A100504");
                    errorMsg = "全部导入失败，共["+errorCount+"]条记录" + errorMsg;
                }else{
                    mm.setCode("A100503");
                    errorMsg = "部分导入成功，共["+successCount+"]条记录导入成功，["+errorCount+"]条记录导入失败" + errorMsg;
                }
                mm.setMessage(errorMsg);
            }else{
                mm.setCode("A100504");
                mm.setMessage("这是一个空Excel");
            }
        }catch (Exception e){
            mm.setCode("A100504");
            if(MyStringUtils.isNotBlank(e.getMessage())){
                int length = e.getMessage().length() >= 500 ? 500 : e.getMessage().length();
                mm.setMessage(e.getMessage().substring(0,length));
            }else{
                int length = e.toString().length() >= 500 ? 500 : e.toString().length();
                mm.setMessage("导入失败:" + e.toString().substring(0,length));
            }
        }
        return mm;
    }


    private Map doImport(DefaultBusinessContext ctx,List<${ClassName}Import> imports){
        Map map = new HashMap();
        map.put("successCount",0);
        map.put("errorCount",0);
        map.put("errorMsg","");

        int successCount = 0;
        int errorCount = 0;
        // 错误信息
        StringBuffer errorMsg = new StringBuffer();

        List<${ClassName}> newList = new ArrayList();
        List<${ClassName}> oldList = new ArrayList();
        for (${ClassName}Import importEntity : imports) {
            if(importEntity.getSuccessFlag()){
                importEntity.setProjectId(ctx.getProjectId());
                importEntity.setCompanyId(ctx.getBranchCompanyId());
                importEntity.setCreaterId(ctx.getAccountId());
                importEntity.setCreaterName(ctx.getAccountName());
                importEntity.setCreateTime(new Date());
                newList.add(importEntity);
                successCount ++;
            }else{
                errorMsg.append(importEntity.getErrorMessage()).append("\n");
                errorCount ++;
            }
        }

        map.put("successCount",successCount);
        map.put("errorCount",errorCount);
        map.put("errorMsg",errorMsg);

        // 新增
        if (CollectionUtils.isNotEmpty(newList)) {
            ${EntityNameForCamelCase}Mapper.insertList(newList);
        }

        // 修改
        if (CollectionUtils.isNotEmpty(oldList)) {
            ${EntityNameForCamelCase}Mapper.batchUpdate(oldList);
        }
        return map;
    }
}
